package Tree;

/**
 * @Classname JZ二叉树的直径
 * @Description TODO
 * @Date 2022/1/31 12:55
 * @Created by xjl
 */
public class JZ二叉树的直径 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    /**
     * @description TODO
     * @param: root
     * @date: 2022/1/31 12:55
     * @return: int
     * @author: xjl
     */
    int len = 0;

    public int diameterOfBinaryTree(TreeNode root) {
        if (root == null) {
            return 0;
        }
        deep(root);
        return len;
    }

    private int deep(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int L = deep(root.left);
        int R = deep(root.right);
        len = Math.max(len, L + R);// 计算d_node即L+R+1 并更新ans
        return Math.max(L, R) + 1;
    }
}
